//
//  ViewController.m
//  JSTest
//
//  Created by 奇林刘 on 2018/9/26.
//  Copyright © 2018年 奇林刘. All rights reserved.
//

#import "ViewController.h"

#define WebUrl1 @"http://www.beituo.xmluma.cn/wangdanyi/index.html#/"


@interface ViewController () 
@property (nonatomic, strong) XBridgeWebView *webView;
@property (nonatomic, strong) UIButton *callJSMethodButton;
@end

@implementation ViewController

#pragma mark - lifeCycle
- (void)viewDidLoad {
    [super viewDidLoad];
    [self allocateParts];
    [self configParts];
    [self refreshSelf];
}

- (void)allocateParts {
    NSString *js = @"getIosToken('helloWorld')";
    WKUserScript *script = [[WKUserScript alloc] initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    [config.userContentController addUserScript:script];

    self.webView = [[XBridgeWebView alloc] initWithFrame:CGRectZero configuration:config];
    [self.view addSubview:self.webView];
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(50);
        make.centerX.equalTo(self.view);
        make.width.equalTo(@(500*9/16.0));
        make.height.equalTo(@(500));
    }];
    
    self.callJSMethodButton = [[UIButton alloc] init];
    [self.view addSubview:self.callJSMethodButton];
    [self.callJSMethodButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.webView.mas_bottom).offset(20);
        make.centerX.equalTo(self.webView);
    }];
}

- (void)configParts {
    self.view.backgroundColor = [UIColor grayColor];
    
    self.callJSMethodButton.backgroundColor = [UIColor whiteColor];
    [self.callJSMethodButton setTitle:@"调用JS函数" forState:UIControlStateNormal];
    [self.callJSMethodButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.callJSMethodButton addTarget:self action:@selector(callJSMethodBUttonClick) forControlEvents:UIControlEventTouchUpInside];
}

- (void)refreshSelf {
    [self loadWeb];
}

#pragma mark - buttonAction
- (void)callJSMethodBUttonClick {
    [self callJSMethod];
}

#pragma mark - relatedMethods
- (void)loadWeb {
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:WebUrl1]];
    [self.webView loadRequest:request];
}

- (void)callJSMethod {
    [self.webView evaluateJavaScript:@"getMessage('成功召唤皮卡丘')" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"error: %@", error.description);
        } else {
            NSLog(@"alertMessage() callSuccess");
        };
    }];
}





@end
